import { dayjs } from "element-plus";

export const camelToSnake = str => {
  return str.replace(/([A-Z])/g, "_$1").toLowerCase();
};

/**
 * 时间戳
 */
export const getCurrentTime = () => {
  return new Date().valueOf();
};
/**
 * 4位随机数
 * @return {number}
 */
export const getRandom = () => {
  return Math.floor(Math.random() * 10000);
};

/**
 * 随机生成ID
 * @return {string}
 */
export const generateId = () => {
  const str = [];
  const hexDigits = "0123456789abcdef";
  for (let i = 0; i < 36; i++) {
    str[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  str[14] = "4";
  str[19] = hexDigits.substr((str[19] & 0x3) | 0x8, 1);
  return str.join("");
};

/**
 * 解析字符串
 */
export const parseOrDefault = (str, defaultValue) => {
  try {
    return JSON.parse(str) || defaultValue;
  } catch {
    return defaultValue;
  }
};

/**
 * 获取文件名
 * @param {String} fileUrl -地址
 */
export const getFileNameByUrl = fileUrl => {
  return fileUrl.slice(fileUrl.lastIndexOf("/") + 1);
};
/**
 * 获取文件后缀
 * @param {String} fileName
 */
export const getFileSuffix = fileName => {
  return fileName.slice(fileName.lastIndexOf(".") + 1);
};

/**
 * @desc 手机号脱敏
 * @demo 155****8810  */
export const hidePhone = phone => {
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
};
export const hideMiddleDigits = phoneNumber => {
  if (phoneNumber?.length === 11) {
    return phoneNumber.slice(0, 3) + "****" + phoneNumber.slice(7);
  } else {
    console.error("手机号码格式不正确");
    return phoneNumber;
  }
};

/**
 * 表格隔行变色
 */
export const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? "even-row" : "odd-row";
};
export function addDays(date, days) {
  let result = new Date(date);
  result.setDate(result.getDate() + Number(days));
  let newDate = dayjs(result).format("YYYY-MM-DD");
  return newDate;
}
